import { useUserStore } from '@/stores/user'

// 配置基础URL
const baseURL = 'http://your-api-domain.com'

// 请求拦截器
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore()
    
    // 合并选项
    options.url = `${baseURL}${options.url}`
    options.header = {
      'Content-Type': 'application/json',
      ...options.header
    }
    
    // 添加token
    if (userStore.token) {
      options.header.Authorization = `Bearer ${userStore.token}`
    }
    
    // 发起请求
    uni.request({
      ...options,
      success: (res) => {
        // 处理响应
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else if (res.data.code === 401) {
            // token失效，需要重新登录
            userStore.logout()
            reject(new Error('登录已过期，请重新登录'))
          } else {
            reject(new Error(res.data.message || '请求失败'))
          }
        } else {
          reject(new Error(`网络请求失败：${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(new Error('网络请求失败'))
      }
    })
  })
}

// 封装GET请求
export const get = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'GET',
    ...options
  })
}

// 封装POST请求
export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'POST',
    ...options
  })
}

// 封装PUT请求
export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'PUT',
    ...options
  })
}

// 封装DELETE请求
export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    data,
    method: 'DELETE',
    ...options
  })
}

// 上传文件
export const upload = (url, filePath, formData = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore()
    
    uni.uploadFile({
      url: `${baseURL}${url}`,
      filePath,
      name: 'file',
      formData,
      header: {
        Authorization: `Bearer ${userStore.token}`,
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const data = JSON.parse(res.data)
          if (data.code === 0) {
            resolve(data)
          } else {
            reject(new Error(data.message || '上传失败'))
          }
        } else {
          reject(new Error(`上传失败：${res.statusCode}`))
        }
      },
      fail: (err) => {
        reject(new Error('上传失败'))
      }
    })
  })
}

export default {
  get,
  post,
  put,
  del,
  upload
} 